/**
 * Created by ZYY on 2016/12/7.
 */
$(function() {
	/*
	 * 机器人状态表格数据处理
	 * */
	/*解析json数据*/
	var pages;//总页数
	var data2 = [];
	var curData = []; //当前data数据（用于分页、模糊搜索等）
	$.ajax({
	    type: "post",
	    url: "/backjson/getJson?method=3",
	    dataType: "json",
	    success: function(data) {
	    	data2 = data;
	    	showStateTb(sortId, 1, 0, data2);
	    	}
	    });
	function sortId(a, b) {
		return a.uid - b.uid;
	}
	//根据运行状态排序
	function sortState(x, y) {
		return x.status - y.status;
	}

	//页面表格数据显示，参数，1：排序方法 2：当前页码 3：加数 4：json数据
	var all_state_page; // 定义一个页码，记录所有当前页码
	function showStateTb(method, nowpage, addpage, data) {
		curData = data;
		all_state_page = nowpage + addpage; // 获得当前页面的页码
		var flag = data.length;
		
		//分页
		var main_pages = Math.ceil(flag / 5); //总页数
		pages = main_pages;
		//判断调用此方法时传来的页数
		if(all_state_page <= main_pages && all_state_page > 0) { //页数大于0小于等于最多页数
			all_state_page = nowpage + addpage;
		} else {
			all_state_page = nowpage; //否则页码不变
		}
		//根据页码，给列表元素数组定下 循环显示的开始值和结束值
		var start = (all_state_page - 1) * 5;
		var end = all_state_page * 5;

		if(end >= flag) {
			end = flag;
		}
		var newdata = data;
		//获得排序后的json数据
		newdata.sort(method);
		//从json中循环取出数据，DOM操作写入页面
		// var num = 0;  //数据总条数
		$("#robot_center table tbody").empty();
		for(var i = start; i < end; i++) {
			var num = i + 1;
			//编写表格dom
			var str;
			if("1" == newdata[i].status.toString() ) {
				str = '<tr><td>' + num + '</td><td>' + newdata[i].uid + '</td><td><span class="play_flag"></span>&nbsp;<span class="play_info">' +
					"正在运行" + '</span></td><td>' + "其他信息" + '</td><td><a href="details.html" class="details">查看详情</a></td></tr>';
			}else if("2" == newdata[i].status.toString() ) {
				str = '<tr><td>' + num + '</td><td>' + newdata[i].uid + '</td><td><span class="play_flag"></span>&nbsp;<span class="play_info">' +
				"在线" + '</span></td><td>' + "其他信息" + '</td><td><a href="details.html" class="details">查看详情</a></td></tr>';
		    }
			else{
				str = '<tr><td>' + num + '</td><td>' + newdata[i].uid + '</td><td><span class="stop_flag"></span>&nbsp;<span class="stop_info">' +
					"已停止" + '</span></td><td>' + "其他信息" + '</td><td><a href="details.html" class="details">查看详情</a></td></tr>';
			}0
			//插入页面表格中
			$("#robot_center table tbody").append(str);
		}
	}

	var ms = {
		init: function(obj, args) {
			return(function() {
				ms.fillHtml(obj, args);
				ms.bindEvent(obj, args);
			})();
		},
		//填充html
		fillHtml: function(obj, args) {
			return(function() {
				obj.empty();
				//上一页
				if(args.current > 1) {
					obj.append('<a href="javascript:;" class="prevPage">上一页</a>');
				} else {
					obj.remove('.prevPage');
					obj.append('<span class="disabled">上一页</span>');
				}
				//中间页码
				if(args.current != 1 && args.current >= 4 && args.pageCount != 4) {
					obj.append('<a href="javascript:;" class="tcdNumber">' + 1 + '</a>');
				}
				if(args.current - 2 > 2 && args.current <= args.pageCount && args.pageCount > 5) {
					obj.append('<span>...</span>');
				}
				var start = args.current - 2,
					end = args.current + 2;
				if((start > 1 && args.current < 4) || args.current == 1) {
					end++;
				}
				if(args.current > args.pageCount - 4 && args.current >= args.pageCount) {
					start--;
				}
				for(; start <= end; start++) {
					if(start <= args.pageCount && start >= 1) {
						if(start != args.current) {
							obj.append('<a href="javascript:;" class="tcdNumber">' + start + '</a>');
						} else {
							obj.append('<span class="current">' + start + '</span>');
						}
					}
				}
				if(args.current + 2 < args.pageCount - 1 && args.current >= 1 && args.pageCount > 5) {
					obj.append('<span>...</span>');
				}
				if(args.current != args.pageCount && args.current < args.pageCount - 2 && args.pageCount != 4) {
					obj.append('<a href="javascript:;" class="tcdNumber">' + args.pageCount + '</a>');
				}
				//下一页
				if(args.current < args.pageCount) {
					obj.append('<a href="javascript:;" class="nextPage">下一页</a>');
				} else {
					obj.remove('.nextPage');
					obj.append('<span class="disabled">下一页</span>');
				}
			})();
		},
		//绑定事件
		bindEvent: function(obj, args) {
			return(function() {
				obj.unbind();   //清除所有绑定的事件
				obj.on("click", "a.tcdNumber", function() {
					var current = parseInt($(this).text());
					ms.fillHtml(obj, {
						"current": current,
						"pageCount": args.pageCount
					});
					if(typeof(args.backFn) == "function") {
						args.backFn(current);
						showStateTb(sortId, current, 0, curData);
					}
				});
				//上一页
				obj.on("click", "a.prevPage", function() {
					var current = parseInt(obj.children("span.current").text());
					ms.fillHtml(obj, {
						"current": current - 1,
						"pageCount": args.pageCount
					});
					if(typeof(args.backFn) == "function") {
						args.backFn(current - 1);
						showStateTb(sortId, current - 1, 0, curData);
					}
				});
				//下一页
				obj.on("click", "a.nextPage", function() {
					var current = parseInt(obj.children("span.current").text());
					ms.fillHtml(obj, {
						"current": current + 1,
						"pageCount": args.pageCount
					});
					if(typeof(args.backFn) == "function") {
						args.backFn(current + 1);
						showStateTb(sortId, current + 1, 0, curData);
					}
				});
			})();
		}
	}
	//创建页码
	$.fn.createPage = function(options) {
			var args = $.extend({
				pageCount: 15,
				current: 1,
				backFn: function() {}
			}, options);
			ms.init(this, args);
		}
		//排序下拉框变化监听事件
	$("#rt_sortType").change(function() {
		$(".prevPage").next().click();
		
		var sortType = $("#rt_sortType").val();
		switch(sortType){
		    case "机器人编号":window.location.reload();//刷新当前页面.
		        break;
		    case "全部状态":showStateTb(sortState,1,0,data2);
		    doPage(pages);
		        break;
		 }
	});
	//状态下拉框变化监听事件
	$("#rt_cen").change(function() {
		var sortType = $("#rt_online").val();
		switch(sortType) {
			case "全部状态":
				window.location.reload();//刷新当前页面.
				break;
			case "正在运行":
				showStateTb(sortState, 1, 0, getDataByState("正在运行"));
				doPage(pages);
				break;
			case "已停止":
				showStateTb(sortState, 1, 0, getDataByState("已停止"));
				doPage(pages);
				break;
		}
	});
	//刷新按钮点击事件
	$("#content #table_robot #robot_center #rt_menu .refresh button").click(function() {
		window.location.reload();//刷新当前页面.
	});
	//模糊搜索点击事件
	$("#rt_search button").click(function() {
		var keyWords = $("#rt_search input").val();
		if(keyWords != null && keyWords != "") {
			searchStateByWords(keyWords);
		}
	});
	//模糊查询方法，主要方法是判断字符串是否出现在已有数据中
	function searchStateByWords(keyWords) {
		$("#table_robot table tbody").empty();
		var newdata = new Array();
		for(var i = 0; i < data2.length; i++) {
			if(data2[i].uid.toString().indexOf(keyWords) >= 0) {
				newdata.push(data2[i]);
			} else if("正在运行".indexOf(keyWords) >= 0) {
				if(data2[i].status == 0) {
					newdata.push(data2[i]);
				}

			} else if("已停止".indexOf(keyWords) >= 0) {
				if(data2[i].status == 2) {
					newdata.push(data2[i]);
				}
			} else {}
		}
		showStateTb(sortId, 1, 0, newdata);
		doPage(pages);
	}
	//根据状态关键字返回data数据
	function getDataByState(keyWords) {
		var newdata = new Array();
		if(keyWords == "全部状态") {
			newdata = data2;
		} else {
			for(var i = 0; i < data2.length; i++) {
				if("已停止" == keyWords) {
					if(data2[i].status == "2") {
						newdata.push(data2[i]);
					}
				} else if("正在运行" == keyWords) {
					if(data2[i].status == "0") {
						newdata.push(data2[i]);
					}
				}
			}
		}
		return newdata;
	}
	//延时操作，获得页码
	setTimeout(function(){
		doPage(pages);
	},500);
	function doPage(pages){
	//调用分页代码
	$(".tcdPageCode").createPage({
		pageCount: pages,
		current: 1,
		backFn: function(p) {}
	});
	}
})